package com.CoreryBlack.service.Impl;

import com.CoreryBlack.Mapper.ClazzMapper;
import com.CoreryBlack.po.Clazz;
import com.CoreryBlack.po.ClazzQueryParam;
import com.CoreryBlack.po.PageBean;
import com.CoreryBlack.po.Student;
import com.CoreryBlack.service.ClazzService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description ClazzServiceImpl
 * @Author CoreryBlack
 * @Date 2024-09-19
 */

@Component
public class ClazzServiceImpl implements ClazzService {

    public ClazzServiceImpl() {
    }

    @Autowired
    private ClazzMapper clazzMapper;

    //删除
    @Override
    public void deleteById(Integer id) {
        if (hasStudents(id)) {
            throw new IllegalStateException("无法删除班级，班级中存在学生");
        }
        clazzMapper.deleteById(id);
    }


    //查询所有
    public List<Clazz> queryString() {
        List<Clazz> clazzList = clazzMapper.findAll();
        return clazzList;
    }

    //分页查询
    public PageBean list(ClazzQueryParam clazzQueryParam) {

        PageHelper.startPage(clazzQueryParam.getPage(),clazzQueryParam.getPageSize());

        Page page1 = clazzMapper.list(clazzQueryParam);

        return new PageBean(page1.getTotal(),page1.getResult());
    }

    //添加
    @Override
    public void saveClazz(Clazz clazz) {

        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.insert(clazz);
    }


    //修改
    @Override
    public void updateClazz(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.updateClazz(clazz);
    }


    //根据ID查询
    @Override
    public Clazz queryById(Integer id) {
        return clazzMapper.queryById(id);
    }

    @Override
    public Clazz getInfo(Integer id) {
        return clazzMapper.getInfo(id);
    }

    @Override
    public boolean hasStudents(Integer clazzId) {
        return clazzMapper.countStudentsByClazzId(clazzId) > 0; // 返回学生数量是否大于0
    }

}
